# TODO: Add comment
# 
# Creaet Time: 2012 4:18:43 PM
# Author: Guochun
# Email: Shenguochun@gmail.com
###############################################################################

#' @name my_Kriging
#' @title automatic Kriging for environmental data of a given community
#' @param env_data a spatialPixelsDataFrame/spatialPointsDataFrame that contains samples of interest variables.
#' @param formula defines the dependent variable as a linear model of independent variables; 
#' suppose the dependent variable has name z, for ordinary and simple kriging use the formula z~1; for simple kriging also define beta (see below); for universal kriging, suppose z is linearly dependent on x and y, use the formula z~x+y
#' @param newcoords a data frame that contains x and y columns of interested locations
#' @description automaticly performs following steps: 1:removing potential trends; 2:computing the empirical variogram; 
#' 3:fitting and selecting a best theoretical variogram model to the empirical variogram; 4:kriging and predicting the values at the 
#' locations of interest
#' @return the predicted map
#'          

my_Kriging=function(env_data,formula,newcoords){
	#computing the empirical variogram
	empirical_vgm=variogram(formula, data=env_data)
	#Ftting and selecting a best theoretical variogram model to the empirical variogram
	fitted_vgm=fit.variogram(empirical_vgm, vgm(1,"Sph",300,1))
	#define the new interested locations
	new_data_grid=patialPoints(newcoords)
	#kriging and predicting the values at the locations of interest
	re=krige(formula,env_data,model=fitted_vgm,new_data_grid)
	return(re["var1.pred"])
}
